/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.cloud.header.reactive;

import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFunction;

import com.iiifi.kite.boot.web.reactive.context.ReactiveRequestContextHolder;
import com.iiifi.kite.core.util.StringUtils;
import com.iiifi.kite.configuration.KiteProperties;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * HttpHeaders 获取器
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
@Configuration
@AllArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class HttpHeadersFilterFunction implements ExchangeFilterFunction {

    private KiteProperties kiteProperties;

    @Override
    public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
        return ReactiveRequestContextHolder.getRequest().flatMap(req -> {
            ClientRequest clientRequest = ClientRequest.from(request)
                    // 透传 header
                    .headers(headers -> filterHeaders(headers, req.getHeaders()))
                    .build();
            return next.exchange(clientRequest);
        });
    }

    /**
     * 透传 header
     *
     * @param newHeaders 传递到下层的 header
     * @param oldHeaders 网关上层的 header
     */
    private void filterHeaders(HttpHeaders newHeaders, HttpHeaders oldHeaders) {
        newHeaders.add(kiteProperties.getHeaders().getAppName(), kiteProperties.getName());
        List<String> allowHeadsList = kiteProperties.getAllowHeads();
        for (String key : allowHeadsList) {
            String value = oldHeaders.getFirst(key);
            if (StringUtils.isNotBlank(value)) {
                newHeaders.add(key, value);
            }
        }
    }
}
